package cn.ygkj.noticespringbootstarter.service;

import cn.ygkj.noticespringbootstarter.entity.NoticeConfig;
import cn.ygkj.noticespringbootstarter.utils.DingTalkUtils;
import com.alibaba.fastjson.JSON;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.api.response.OapiRobotSendResponse;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

import static cn.ygkj.noticespringbootstarter.constract.MSGType.MSG_TYPE_TEXT;

/**
 * @author : ☪lei☠
 * @ClassName : NoticeService
 * @Description :
 * @createTime : 2022年07月24日 16:37:00
 */
@Component
@Slf4j
public class NoticeService {

    /**
     * 客户端实例
     */
    @Autowired
    private DingTalkClient client;


    /**
     * 发送普通文本消息
     *
     * @param content    文本消息
     * @param isAtAll    是否@ 全部联系人
     * @return OapiRobotSendResponse
     */
    public OapiRobotSendResponse sendMessageByText(String content, boolean isAtAll) {
        if (StringUtils.isBlank(content)) {
            return null;
        }

        //参数	参数类型	必须	说明
        //msgtype	String	是	消息类型，此时固定为：text
        //content	String	是	消息内容
        //atMobiles	Array	否	被@人的手机号(在content里添加@人的手机号)
        //isAtAll	bool	否	@所有人时：true，否则为：false
        OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
        text.setContent(content);
        OapiRobotSendRequest request = new OapiRobotSendRequest();
        if (isAtAll) {
            OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();
            at.setIsAtAll(isAtAll);
            request.setAt(at);
        }


        request.setMsgtype(MSG_TYPE_TEXT);
        request.setText(text);

        OapiRobotSendResponse response = new OapiRobotSendResponse();
        try {
            response = client.execute(request);
        } catch (ApiException e) {
            log.error("[发送普通文本消息]: 发送消息失败, 异常捕获{}", e.getMessage());
        }
        return response;
    }

}
